package com.ukao.pad.ui.leaveFactory;


import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.gprinterio.GpDevice;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.pad.R;
import com.ukao.pad.adapter.LogisticsAdapter;
import com.ukao.pad.adapter.StartFactoryAdapter;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.BatchlTabBean;
import com.ukao.pad.bean.FactoryBatchInBean;
import com.ukao.pad.bean.PrintAloneBean;
import com.ukao.pad.bean.ProductBatchInBean;
import com.ukao.pad.consts.Constant;
import com.ukao.pad.dialog.AddBatchDialogtFragment;
import com.ukao.pad.dialog.DialogTool;
import com.ukao.pad.dialog.DownloadDialogFragment;
import com.ukao.pad.dialog.StartCountDialogFragment;
import com.ukao.pad.eventbus.MembershipCardEvent;
import com.ukao.pad.listener.MyOnItemClickListener;
import com.ukao.pad.listener.OnConfirmClickListener;
import com.ukao.pad.presenter.LeverFactoryPesenter;
import com.ukao.pad.printer.CheckPrinterHelper;
import com.ukao.pad.printer.PrinterReceipt;
import com.ukao.pad.ui.setting.SettingFragment;
import com.ukao.pad.usbrfidreader.UsbrfidReaderHelper;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.KeyBoardUtil;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.LeverFactoryView;
import com.ukao.pad.widget.ClearEditText;
import com.ukao.pad.widget.CustomPopWindow;
import com.ukao.pad.widget.MyLRecyclerView;
import com.ukao.pad.widget.PercentLinearLayout;
import com.ukao.pad.widget.StateButton;
import com.ukao.pad.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportActivity;

import static com.ukao.pad.R.id.check_btn;
import static com.ukao.pad.R.id.left_titles;
import static com.ukao.pad.R.id.start_count_btn;

/**
 * 出厂
 */
public class LeaveFactoryFragment extends MvpFragment<LeverFactoryPesenter> implements LeverFactoryView{

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    Unbinder unbinder;
    @BindView(R.id.batch_btn)
    StateImageView batchBtn;
    @BindView(left_titles)
    TextView leftTitles;
    @BindView(R.id.search_edit_left)
    ClearEditText searchEditLeft;
    @BindView(R.id.search_button)
    StateImageView searchButton;

    @BindView(R.id.no_data)
    TextView noData;
    @BindView(R.id.logistics_recycler_view)
    RecyclerView logisticsRecyclerView;
    @BindView(R.id.productsum)
    TextView productsum;
    @BindView(R.id.productCnt)
    TextView productCnt;
    @BindView(R.id.already_productsum)
    TextView alreadyProductsum;
    @BindView(R.id.already_productCnt)
    TextView alreadyProductCnt;
    @BindView(R.id.left_include)
    LinearLayout leftInclude;
    @BindView(R.id.sure_factory)
    StateButton sureFactory;
    @BindView(R.id.back_btn)
    StateImageView backBtn;
    @BindView(R.id.left_search_line)
    View leftSearchLine;
    @BindView(R.id.deficiency_btn)
    StateButton deficiencyBtn;
    @BindView(R.id.check_btn)
    StateButton checkBtn;
    @BindView(R.id.start_count_btn)
    StateButton startCountBtn;
    @BindView(R.id.delete_btn)
    StateButton deleteBtn;

    @BindView(R.id.rfid_btn)
    StateImageView rfid_btn;

    @BindView(R.id.add_btn)
    StateButton addBtn;

    @BindView(R.id.print_factory_receipt_btn)
    StateButton printFactoryReceiptBtn;


    @BindView(R.id.search_edit_text)
    ClearEditText searchEditText;
    @BindView(R.id.search_clothing_button)
    StateImageView searchClothingButton;
    @BindView(R.id.no_right_data)
    TextView noRightData;
    @BindView(R.id.right_include)
    PercentLinearLayout rightInclude;
    @BindView(R.id.count_RecyclerView)
    MyLRecyclerView countRecyclerView;
    @BindView(R.id.left_search_layout)
    LinearLayout leftSearchLayout;
    @BindView(R.id.right_search_layout)
    LinearLayout rightSearchLayout;
    @BindView(R.id.tab_lin)
    View tabLin;
    @BindView(R.id.code_name)
    TextView codeName;
    @BindView(R.id.webView)
    WebView webView;
    private boolean isleftSearch; /*\是否是左边搜索*/
    private String mParam2;
    public int loseFactoryCount;
    private StartFactoryAdapter mStartFactoryAdapter;
    private LogisticsAdapter mLogisticsAdapter;
    private CustomPopWindow mReportLossWindow;
    private ArrayList<ProductBatchInBean> mCountData;
    private ArrayList<FactoryBatchInBean> mLogisticsData;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private int alreadyCount; /*已经点的数目*/
    private int mProductSum;
    private CustomPopWindow mAllCheckWindow;
    private boolean isshowAllCheck;
    private String printList;
    private String leaveFactoryHite;
    public String outId;
    public String clotgingId;
    private String batchInId;
    private String srtsearchEditright;
    private String strsearchEditText;
    private int notCheck;
    private String rightId;
    private BatchlTabBean.ListBean mBatchlTab;
    private boolean isFinish;/*是否完成*/
    private WebSettings settings;
    private String searchKeyright;
    private StartCountDialogFragment mStartCountDialog;
    private   boolean  isVisible;
    public static LeaveFactoryFragment newInstance(Parcelable param1, String  mParam2) {
        LeaveFactoryFragment fragment = new LeaveFactoryFragment();
        Bundle args = new Bundle();
         args.putParcelable(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, mParam2);
        fragment.setArguments(args);
        return fragment;
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mBatchlTab = getArguments().getParcelable(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    protected LeverFactoryPesenter createPresenter() {
        return new LeverFactoryPesenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_leave_factory, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initAdapter();
        initListener();
        return view;
    }



    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        isVisible=true;

        if (CheckUtils.isNull(mBatchlTab))
            UsbrfidReaderHelper.getInstance().readCardNum();
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        isVisible=false;
        UsbrfidReaderHelper.getInstance().cancelReadCardNum();
    }

    @Override
    protected void initView() {

        if (!CheckUtils.isNull(mBatchlTab)) {
            batchBtn.setVisibility(View.GONE);
            backBtn.setVisibility(View.VISIBLE);
            leftTitles.setText("批号：" + mBatchlTab.getCode());
            leftSearchLayout.setVisibility(View.GONE);
            rightSearchLayout.setVisibility(View.GONE);
            mvpPresenter.detailleft(mBatchlTab.getCode());
            isleftSearch = true;
        }

        showLoadingLayout();
        leaveFactoryHite = resources.getString(R.string.sure_leave_factory);
        printList = resources.getString(R.string.print_list);
        mCountData = new ArrayList<>();
        mLogisticsData = new ArrayList<>();
    }

    @Override
    protected void initAdapter() {
        super.initAdapter();
        initLinearRecyclerView(countRecyclerView);
        countRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        mStartFactoryAdapter = new StartFactoryAdapter(_mActivity, mCountData, true);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mStartFactoryAdapter);
        countRecyclerView.setAdapter(mLRecyclerViewAdapter);
        initLinearRecyclerView(logisticsRecyclerView);
        mLogisticsAdapter = new LogisticsAdapter(_mActivity, mLogisticsData);
        logisticsRecyclerView.setAdapter(mLogisticsAdapter);
        countRecyclerView.setFocusable(false);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mStartFactoryAdapter.setOnItemClickListener(mOnItemClickListener);
        countRecyclerView.setOnRefreshListener(mOnRefreshListener);
        searchEditLeft.setOnEditorActionListener(mOnEditorActionListener);
        searchEditText.setOnEditorActionListener(mOnEditorActionListener);
        searchEditText.requestFocus();

    }


    TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {

                if (v == searchEditLeft) {

                    searchLeftBarode();
                } else if (v == searchEditText) {

                    searchRightBatch();
                }


            }
            return false;
        }
    };

    private OnRefreshListener mOnRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {


            mStartFactoryAdapter.getDatas().clear();
            mLRecyclerViewAdapter.notifyDataSetChanged();
            mvpPresenter.createBatchOut1(outId,false);
//            if (!isleftSearch && !CheckUtils.isEmpty(searchKeyright)) {
//                mvpPresenter.createBatchOut(searchKeyright, false);
//
//            } else if (!CheckUtils.isEmpty(rightId)) {
//                mvpPresenter.createBatchOut1(rightId, false);
//            } else {
//                refreshFinish();
//            }


        }
    };


    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            if (mStartFactoryAdapter.getItem(i)!=null) {
                ProductBatchInBean item = mStartFactoryAdapter.getItem(i);
               // if (item.getFactoryStatus() ) return;
                item.setCheck(!item.isCheck());
                mLRecyclerViewAdapter.notifyDataSetChanged();
            }
        }

    };

    private String getLossClothingId() {
        clotgingId = "";
        StringBuffer mStringBuffer = new StringBuffer();
        for (int j = 0; j < mCountData.size(); j++) {
            ProductBatchInBean mCountitem = mCountData.get(j);
            if (mCountitem.isCheck()) {

                mStringBuffer.append(mCountitem.getId() + ",");
            }

        }
        if (mStringBuffer.length() != 0)
            clotgingId = mStringBuffer.deleteCharAt(mStringBuffer.length() - 1).toString();

        return clotgingId;
    }
    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(MembershipCardEvent event) {

        switch (event.getMessage()) {
            case cardNum:/*成功*/

                if (!CheckUtils.isNull(mStartCountDialog) && mStartCountDialog.getDialog() != null && mStartCountDialog.getDialog().isShowing())return;
                if (isVisible){
                    String rfidSecretCard = (String) event.getData();
                    searchEditText.setText(rfidSecretCard);
                    searchRightBatch();
                }




                break;


        }
    }

    @OnClick({R.id.search_button, start_count_btn, R.id.check_btn, R.id.deficiency_btn, R.id.sure_factory, R.id.batch_btn,
            R.id.search_clothing_button, R.id.back_btn,R.id.print_factory_receipt_btn,R.id.delete_btn,R.id.add_btn,R.id.rfid_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case  R.id.rfid_btn :
                UsbrfidReaderHelper.getInstance().readCardNum();
                break;
            case  R.id.add_btn:  /*添加衣物*/
                if (CheckUtils.isEmpty(outId))return;
                AddBatchDialogtFragment  mAddBatchDialogt=AddBatchDialogtFragment.newInstance(outId,"");
                mAddBatchDialogt.setOnConfirmClickListener(mOnConfirmClickListener);
                mAddBatchDialogt.show(getChildFragmentManager(),mAddBatchDialogt.getClass().getName());


                break;
            case  R.id.delete_btn:/*删除衣物*/

                StringBuffer  mStringBuffer=new StringBuffer();
                for (ProductBatchInBean mitem : mStartFactoryAdapter.getDatas()) {
                    if (    mitem.isCheck()){
                        mStringBuffer.append(mitem.getId()).append(",");
                    }

                }
                String orderProIds = mStringBuffer.toString();
                if (!CheckUtils.isEmpty(orderProIds)){
                    if (orderProIds.endsWith(","))
                        orderProIds = orderProIds.substring(0, orderProIds.length() - 1);
                    mvpPresenter.deleteBatch( orderProIds);
                }

                break;

            case  R.id.print_factory_receipt_btn:  /*打印出厂小票*/
                if (CheckPrinterHelper.isReceipt()) {
                    mvpPresenter.printbatchOut(batchInId);
                    }

                break;
            case R.id.back_btn:
                finish();
                break;
            case R.id.batch_btn:/*批次tab*/
                start(new FactoryTabFragment());
                break;
            case check_btn:  /*已全部核对*/
                isshowAllCheck = true;
                mAllCheckWindow = DialogTool.getSingleton().showPopReportLoss(_mActivity, sureFactory, "是否全部核对衣物数量？", mLossListener);
                break;
            case R.id.search_button:
                searchLeftBarode();
                break;
            case R.id.search_clothing_button:
                searchRightBatch();
                break;

            case start_count_btn:/*点数*/


                if (CheckUtils.isEmpty(mStartFactoryAdapter.getDatas())) return;
                ArrayList<ProductBatchInBean> mdata = (ArrayList<ProductBatchInBean>) mStartFactoryAdapter.getDatas();
                mStartCountDialog= new StartCountDialogFragment();
                Bundle mBundle = new Bundle();
                mBundle.putParcelableArrayList(ARG_PARAM1, mdata);
                mBundle.putBoolean(ARG_PARAM2, true);
                mStartCountDialog.setArguments(mBundle);
                mStartCountDialog.setOnConfirmClickListener(mOnConfirmClickListener);
                mStartCountDialog.setOnCounntSucceedListener(mOnCounntSucceed);
                mStartCountDialog.show(getChildFragmentManager(),mStartCountDialog.getClass().getName());

                break;
            case R.id.deficiency_btn:/*上报缺失*/

                if (CheckUtils.isEmpty(getLossClothingId())) return;
                isshowAllCheck = false;
                mReportLossWindow = DialogTool.getSingleton().showPopReportLoss(_mActivity, sureFactory, null, mLossListener);

                break;
            case R.id.sure_factory:
                String strsureFactory = sureFactory.getText().toString();

                if (printList.equals(strsureFactory)) { /*打印衣物清单*/
                    if (CheckUtils.isAppInstalled()) {
                        printService(Constant.printUrl(batchInId));
                    } else {
                        DownloadDialogFragment mDownloadDialog = DownloadDialogFragment.newInstance("", "");
                        mDownloadDialog.setOnConfirmClickListener(mOnConfirmClickListener);
                        mDownloadDialog.show(getChildFragmentManager(),mDownloadDialog.getClass().getName());
                    }


                } else if (strsureFactory.equals(leaveFactoryHite) && !CheckUtils.isEmpty(batchInId)) {
                    mvpPresenter.sureLeaveFactory(_mActivity, batchInId);
                }

                break;
        }
    }

    private OnConfirmClickListener mOnConfirmClickListener=new OnConfirmClickListener() {
        @Override
        public void onChildItemClick(int id, Object msg) {
            switch (id) {
                case R.id.edit_name_submit:
                    start(SettingFragment.newInstance(2, ""), SINGLETASK);
                    break;

                case  R.id.submit:  /*添加衣物*/

                    break;
                case Constant.START_COUNT_DESTROY:  /*刷新当前列表*/

                        deleteSucceed();
                    break;

                case   Constant.ON_DESTORY:
                    if (CheckUtils.isNull(mBatchlTab))
                        UsbrfidReaderHelper.getInstance().readCardNum();

                    break;
            }



        }
    };


    /**
     * 左边条码
     */
    private void searchLeftBarode() {
        strsearchEditText = getText(searchEditLeft);
        if (CheckUtils.isEmpty(strsearchEditText)) return;
        KeyBoardUtil.hideKeyboard(_mActivity);
        isleftSearch = true;
        mvpPresenter.detailleft(strsearchEditText);
    }

    /**
     * 右边批次
     */
    private void searchRightBatch() {
        srtsearchEditright = getText(searchEditText);
        if (CheckUtils.isEmpty(srtsearchEditright)) return;
        KeyBoardUtil.hideKeyboard(_mActivity);
        isleftSearch = false;
        mvpPresenter.createBatchOut(srtsearchEditright, true);
    }

    /**
     * 点数成功
     */
    private StartCountDialogFragment.OnCounntSucceedListener mOnCounntSucceed = new StartCountDialogFragment.OnCounntSucceedListener() {
        @Override
        public void onCounntSucceed(int  pos ){
                ProductBatchInBean item = mStartFactoryAdapter.getItem(pos);
                item.setStatusText("已核对");
                item.setStatus(1);
                alreadyCount = alreadyCount + 1;
                mLRecyclerViewAdapter.notifyDataSetChanged();
                showTotalCountStyle();


        }
    };

    private View.OnClickListener mLossListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                case R.id.submit:

                    if (isshowAllCheck) {
                        mAllCheckWindow.dissmiss();

                        mvpPresenter.checkAllConfirmProFactory(_mActivity, outId);

                    } else {

                        mvpPresenter.loseLeaveFactory(clotgingId, outId);
                        mReportLossWindow.dissmiss();
                    }

                    break;
            }

        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();



    }

    /**
     * 出厂批次 左边
     */
    @Override
    public void loadDetailleftData(FactoryBatchInBean mitem) {
        mLogisticsData.clear();

        outId = mitem.getId();
        if (!CheckUtils.isNull(mitem.getFactoryName())) {

            FactoryBatchInBean mBatchInBean1 = new FactoryBatchInBean(mitem.getFactoryName(), mitem.getFactoryWorkTime(), true);
            mBatchInBean1.setStatusText(mitem.getStatusText());
            FactoryBatchInBean mBatchInBean2 = null;
            mBatchInBean2 = !CheckUtils.isNull(mitem.getLogisticsWorkName()) ? new FactoryBatchInBean(mitem.getLogisticsWorkName(), mitem.getLogisticsWorkTime(), true) : new FactoryBatchInBean("", 0, false);
            FactoryBatchInBean mBatchInBean3 = null;
            mBatchInBean3 = !CheckUtils.isNull(mitem.getStoreName()) ? mBatchInBean2.isgreed() ? new FactoryBatchInBean(mitem.getStoreName(), mitem.getStoreWorkTime(), true) : new FactoryBatchInBean(mitem.getStoreName(), mitem.getStoreWorkTime(), false) : new FactoryBatchInBean("未知", 0, false);

            codeName.setText("出厂批次：" + mitem.getCode());
            isFinish = mitem.getIsFinish();
            batchInId = mitem.getId();
            mLogisticsData.add(mBatchInBean1);
            mLogisticsData.add(mBatchInBean2);
            mLogisticsData.add(mBatchInBean3);
            mLogisticsAdapter.setDatas(mLogisticsData);
            leftInclude.setVisibility(View.VISIBLE);
            mProductSum = mitem.getallProductSum();
            productsum.setText(mitem.getProductSum());
            productCnt.setText(mitem.getProductCnt() + mitem.getAnnexCnt());
            alreadyProductCnt.setText(mitem.getProductCnt() + mitem.getAnnexCnt());
            if (!isleftSearch) {
                showTotalCountStyle();
            } else {
                rightId = mitem.getId();
                mvpPresenter.createBatchOut1(rightId, false);
            }

        }

    }


    /**
     * 右边的数据
     *
     * @param mFactoryBatchInBean
     */
    @Override
    public void loadbatchListSuccess(List<ProductBatchInBean> mFactoryBatchInBean,String  batchCode) {

        alreadyCount = 0;
        loseFactoryCount = 0;
        notCheck = 0;
        if (CheckUtils.isEmpty(mFactoryBatchInBean)) {
            showNullLayout();

        } else {

            showContentLayout();
            if (!isleftSearch) {
                outId = mFactoryBatchInBean.get(0).getOutId();
                mvpPresenter.detailleft1(outId);
            }
            for (int i = 0; i < mFactoryBatchInBean.size(); i++) {
                int mstatus = mFactoryBatchInBean.get(i).getFactoryStatus();
                switch (mstatus) {
                    case 2: /*异常*/
                        loseFactoryCount = loseFactoryCount + 1;
                        break;
                    case 1: /*已经核对*/
                        alreadyCount = alreadyCount + 1;
                        break;
                    case 0: /*未核对*/
                        notCheck = notCheck + 1;

                        break;
                }
            }

        }

        mStartFactoryAdapter.getDatas().clear();
        mStartFactoryAdapter.getDatas().addAll(mFactoryBatchInBean);
        // sortProductBatchIn();
        mLRecyclerViewAdapter.notifyDataSetChanged();
        if (isleftSearch) {
            searchEditLeft.setText("");
            searchEditLeft.requestFocus();
        }else{
            searchKeyright=batchCode;
        }
        showTotalCountStyle();


    }


    /**
     * 显示所有点数 以及样式
     */
    private void showTotalCountStyle() {



        alreadyProductsum.setText("共点数 " + alreadyCount + " 件");
        if (notCheck != 0) { /*未核对数 就显示异常按钮*/
            deficiencyBtn.setVisibility(View.VISIBLE);
            checkBtn.setVisibility(View.VISIBLE);
            startCountBtn.setVisibility(View.VISIBLE);
            sureFactory.setVisibility(View.GONE);
            printFactoryReceiptBtn.setVisibility(View.GONE);
            setShowClothingBtn();
        } else if (notCheck == 0) {
            checkBtn.setVisibility(View.GONE);
            deficiencyBtn.setVisibility(View.GONE);
            startCountBtn.setVisibility(View.GONE);
            sureFactory.setVisibility(View.VISIBLE);
            sureFactory.setText(isFinish ? printList : leaveFactoryHite);
            printFactoryReceiptBtn.setVisibility(isFinish?View.VISIBLE:View.GONE);
            setShowClothingBtn();
        }
        if (mProductSum > alreadyCount) {/*点的数量小于总数 但是上报缺失数量等于总数*/
            alreadyProductsum.setTextColor(resources.getColor(R.color.normal_red));
            alreadyProductCnt.setTextColor(resources.getColor(R.color.normal_red));
            if (!isFinish && alreadyCount > 0) {
                sureFactory.setVisibility(alreadyCount + loseFactoryCount == mProductSum ? View.VISIBLE : View.GONE);
                sureFactory.setText(leaveFactoryHite);
                printFactoryReceiptBtn.setVisibility(alreadyCount + loseFactoryCount == mProductSum ? View.VISIBLE : View.GONE);
                setShowClothingBtn();
            }

            if (alreadyProductsum.getVisibility() == View.GONE)
                alreadyProductsum.setVisibility(View.VISIBLE);
                alreadyProductCnt.setVisibility(View.VISIBLE);
        } else if (mProductSum == alreadyCount) {/*全部核对数量*/
            if (!CheckUtils.isNull(mStartCountDialog)&&mStartCountDialog.getDialog()!=null&&mStartCountDialog.getDialog().isShowing()){
                mStartCountDialog.dismiss();
            }
            alreadyProductsum.setTextColor(resources.getColor(R.color.green));
            alreadyProductCnt.setTextColor(resources.getColor(R.color.green));
            sureFactory.setVisibility(View.VISIBLE);
            sureFactory.setText(isFinish ? printList : leaveFactoryHite);
            printFactoryReceiptBtn.setVisibility(isFinish?View.VISIBLE:View.GONE);
            setShowClothingBtn();
            checkBtn.setVisibility(View.GONE);
            startCountBtn.setVisibility(View.GONE);
            deficiencyBtn.setVisibility(View.GONE);
        }
        searchEditText.setText("");
        hideSoftInput();

    }

    private void setShowClothingBtn() {
        if (printFactoryReceiptBtn.getVisibility()== View.VISIBLE){
            deleteBtn.setVisibility(View.GONE);
            addBtn.setVisibility(View.GONE);
            if (mStartFactoryAdapter.getDatas().size()!=0){
                for (ProductBatchInBean item : mStartFactoryAdapter.getDatas()) {
                    item.setFinish(true);
                }
                mStartFactoryAdapter.notifyDataSetChanged();
            }

        }
        else{
            deleteBtn.setVisibility(View.VISIBLE);
            addBtn.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 显示右边空数据布局
     */
    @Override
    protected void showNullLayout() {
        super.showNullLayout();
        tabLin.setVisibility(View.GONE);
        rightInclude.setVisibility(View.GONE);
        noRightData.setVisibility(View.VISIBLE);
        startCountBtn.setVisibility(View.GONE);
        deficiencyBtn.setVisibility(View.GONE);
        checkBtn.setVisibility(View.GONE);
        countRecyclerView.setVisibility(View.GONE);
        addBtn.setVisibility(View.GONE);
        deleteBtn.setVisibility(View.GONE);

    }


    public void showLoadingLayout() {
        addBtn.setVisibility(View.GONE);
        deleteBtn.setVisibility(View.GONE);
        checkBtn.setVisibility(View.GONE);
        startCountBtn.setVisibility(View.GONE);
        deficiencyBtn.setVisibility(View.GONE);
        rightInclude.setVisibility(View.GONE);
        countRecyclerView.setVisibility(View.GONE);
    }

    @Override
    protected void showContentLayout() {
        super.showContentLayout();
        countRecyclerView.setVisibility(View.VISIBLE);
        rightInclude.setVisibility(View.VISIBLE);
        noRightData.setVisibility(View.GONE);
        tabLin.setVisibility(View.VISIBLE);


    }


    @Override
    public void refreshFinish() {

        countRecyclerView.refreshComplete(10);

    }

    @Override
    public void loadFail(String errs) {
        T.show(errs);
    }


    /**
     * 确认出厂成功
     */
    @Override
    public void sureFactorySuccess() {
        isFinish=true;
        searchEditText.setText("");
        searchEditLeft.setText("");
        searchEditText.requestFocus();
        KeyBoardUtil.hideInputmethod(searchEditText);
        KeyBoardUtil.hideInputmethod(searchEditLeft);
        DialogTool.getSingleton().showPopEnterFactory(true, (SupportActivity) _mActivity, sureFactory);
        sureFactory.setText(printList);
        printFactoryReceiptBtn.setVisibility(View.VISIBLE);
        setShowClothingBtn();
    }



    private void clearInitState() {
        checkBtn.setVisibility(View.GONE);
        mLogisticsAdapter.getDatas().clear();
        mLogisticsAdapter.notifyDataSetChanged();
        mStartFactoryAdapter.getDatas().clear();
        mLRecyclerViewAdapter.notifyDataSetChanged();
        sureFactory.setVisibility(View.GONE);
        startCountBtn.setVisibility(View.GONE);
        deficiencyBtn.setVisibility(View.GONE);
        leftInclude.setVisibility(View.GONE);
        rightInclude.setVisibility(View.GONE);
        alreadyCount = 0;
        loseFactoryCount = 0;
        notCheck = 0;
        rightId = "";
        clotgingId = "";
        outId = "";
        batchInId = "";


    }


    /**
     * 上报成功
     *

     */
    @Override
    public void loseFactorySuccess(String message) {
        T.show(message);
        countRecyclerView.forceToRefresh();
    }

    /**
     * 核对全部
     *
     * @param msg
     */
    @Override
    public void checkAllFactory(String msg) {
        countRecyclerView.forceToRefresh();
        checkBtn.setVisibility(View.GONE);
        startCountBtn.setVisibility(View.GONE);
        deficiencyBtn.setVisibility(View.GONE);
    }


    /**
     * 打印衣物
     *
     * @param mPrintAloneBean
     */
    @Override
    public void loadPrintbatchOutSuccess(PrintAloneBean mPrintAloneBean) {

        GpDevice mGpDevice = new GpDevice();
        PrinterReceipt.getInstance().printleaveFactory(mPrintAloneBean, mGpDevice);
    }

    /**
     * 删除衣物
     */
    @Override
    public void deleteSucceed() {
        mvpPresenter.createBatchOut1(outId,true);
        mvpPresenter.detailleft1(outId);
    }


    private void   printService (String loadurl) {


        settings= webView.getSettings();
       Constant.initWeb(settings,webView);
        webView.requestFocus();
        webView.loadUrl(loadurl);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showProgressDialog();
            }

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dismissProgressDialog();
                createWebPrintJob(webView);
                webView.setLayerType(View.LAYER_TYPE_NONE, null);
                if (!settings.getLoadsImagesAutomatically()) {
                    settings.setLoadsImagesAutomatically(true);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                T.show("加载失败");
                dismissProgressDialog();
            }
        });


    }



    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void createWebPrintJob(WebView webView) {

        try {
            // Get a PrintManager instance
            PrintManager printManager = (PrintManager)_mActivity.
                    getSystemService(Context.PRINT_SERVICE);

            // Get a print adapter instance
            PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
            // Create a print job with name and adapter instance
            String jobName = getString(R.string.app_name) + " Document";
            PrintJob printJob = printManager.print(jobName, printAdapter,
                    new PrintAttributes.Builder().build());
        }catch (Exception e){
            T.show("预览出错");
        }



    }


}
